package com.leetcode.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author zhang.xin
 * @Description: 给定一个二叉树，返回其按层次遍历的节点值。
 * @Date 2019/12/30
 */
public class Leetcode102 {

    public List<List<Integer>> levelOrder(TreeNode root) {

        if (root == null) {
            return new ArrayList<>();
        }

        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> returnList = new ArrayList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> levelList = new ArrayList<>();
            while (count > 0) {
                TreeNode node = queue.poll();
                if (node != null) {
                    levelList.add(node.val);
                    if (node.left != null) {
                        queue.add(node.left);
                    }
                    if (node.right != null) {
                        queue.add(node.right);
                    }
                }
                count--;
            }
            returnList.add(levelList);

        }
        return returnList;
    }

    private TreeNode createTree() {
        TreeNode root = new TreeNode(3);
        TreeNode t1 = new TreeNode(9);
        TreeNode t2 = new TreeNode(20);
        TreeNode t5 = new TreeNode(15);
        TreeNode t6 = new TreeNode(7);

        root.left = t1;
        root.right = t2;
        t2.left = t5;
        t2.right = t6;

        return root;
    }

    public static void main(String[] args) {
        Leetcode102 leet = new Leetcode102();
        TreeNode root = leet.createTree();
        leet.levelOrder(root);


    }

}
